<script>
import { ref, toRefs } from 'vue'
import request from '@/utils/request'
import { ElNotification, ElMessageBox } from 'element-plus'

export default {
  name: 'ExportExcel',
  props: {
    tableThead: {
      type: Array,
      default() { return [] }
    },
    list: {
      type: Array,
      default() { return [] }
    },
    fileName: {
      type: String,
      default: 'excel'
    },
    config: {
      type: Object,
      default: () => ({})
    },
    debug: Boolean
  },
  emits: ['click'],
  setup(props, { slots, attrs, emit }) {
    const defaultNodes = !(slots.default) ? <span>导出</span> : slots.default()

    // console.log(props)
    const downloadLoading = ref(false)

    const handleDownload = () => {
      const { tableThead: dynamicMulti, list: dynamicData, fileName } = toRefs(props)
      downloadLoading.value = true
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_dynamicexcel({
          dynamicMulti,
          dynamicData,
          fileName
        })
        downloadLoading.value = false
      }).finally(() => downloadLoading.value = false)
    }

    const extraDownload = async (form = {}, formatter) => {
      let notice = null
      try {
        await ElMessageBox.confirm('确定导出数据吗？', '系统提示', {
          type: 'info'
        })
        downloadLoading.value = true
        notice = ElNotification({
          iconClass: 'el-icon-loading',
          title: '导出提示',
          showClose: false,
          position: 'bottom-right',
          offset: 80,
          duration: 0,
          message: '数据导出中,请稍后……'
        })
        const postData = formatData(form, formatter, true)
        const reqBody = {
          method: 'post',
          responseType: 'blob'
        }
        const { fileName = '导出信息', params, ...args } = props.config
        if (params) Object.assign(postData, params)
        Object.assign(reqBody, args)
        if(args.method && args.method === 'get') reqBody.params = postData
        else reqBody.data = postData

        if(props.debug) return console.log(reqBody);

        const binaryData = await request(reqBody)
        const blob = new Blob([binaryData], { type: 'application/octet-stream' })
        if ('download' in document.createElement('a')) {
          const downloadElement = document.createElement('a')
          const href = window.URL.createObjectURL(blob) // 创建下载的链接
          downloadElement.href = href
          downloadElement.download = fileName + '.xls' // 下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() // 点击下载
          document.body.removeChild(downloadElement) // 下载完成移除元素
          window.URL.revokeObjectURL(href) // 释放掉blob对象
        } else {
          navigator.msSaveBlob(blob, fileName + '.xlsx')
        }
      } catch (error) {
        console.error('Export【catch】', error)
      } finally {
        downloadLoading.value = false
        if (notice != null) notice.close()
      }
    }

    const btnClick = () => {
      const { url } = props.config

      if(url) {
        emit('click', extraDownload)
      } else {
        handleDownload()
      }
    }

    return () => (
    <el-button
    type="primary"
    loading={downloadLoading.value}
    props={attrs}
    onClick={btnClick}
    v-slots={
      {
        default: () => defaultNodes
      }
    }
    />)
  }

}

function formatData(raw, formatter, delOldPro = false) {
  const newData = { ...raw }
  if (!formatter) return newData
  if (type(formatter) === 'object') {
    for (const prop in formatter) {
      if (newData[prop]) {
        Object.assign(newData, formatter[prop](newData[prop]))
        if (delOldPro) delete newData[prop]
      }
    }
  }
  if (type(formatter) === 'function') {
    formatter(newData)
  }
  return newData
}
</script>

